package com.sixmac.service.impl;

import com.sixmac.core.Constant;
import com.sixmac.dao.MessageInfoDao;
import com.sixmac.entity.MessageInfo;
import com.sixmac.service.MessageInfoService;
import com.sixmac.utils.MessageTimerWork;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2016/6/1 0001 下午 4:53.
 */
@Service
public class MessageInfoServiceImpl implements MessageInfoService {

    @Autowired
    private MessageInfoDao messageInfoDao;

    @Override
    public List<MessageInfo> findAll() {
        return messageInfoDao.findAll();
    }

    @Override
    public Page<MessageInfo> find(int pageNum, int pageSize) {
        return messageInfoDao.findAll(new PageRequest(pageNum - 1, pageSize, Sort.Direction.DESC, "id"));
    }

    @Override
    public Page<MessageInfo> find(int pageNum) {
        return find(pageNum, Constant.PAGE_DEF_SIZE);
    }

    @Override
    public MessageInfo getById(int id) {
        return messageInfoDao.findOne(id);
    }

    @Override
    public MessageInfo deleteById(int id) {
        MessageInfo messageInfo = getById(id);
        messageInfoDao.delete(messageInfo);

        // 删除消息时，杀死线程
        MessageTimerWork.killWork("one" + id);

        return messageInfo;
    }

    @Override
    public MessageInfo create(MessageInfo messageInfo) {
        return messageInfoDao.save(messageInfo);
    }

    @Override
    public MessageInfo update(MessageInfo messageInfo) {
        return messageInfoDao.save(messageInfo);
    }

    @Override
    @Transactional
    public void deleteAll(int[] ids) {
        for (int id : ids) {
            deleteById(id);
        }
    }

    @Override
    public List<MessageInfo> findListByMessageId(Integer messageId) {
        return messageInfoDao.findListByMessageId(messageId);
    }

    @Override
    @Transactional
    public void deleteByMessageId(Integer messageId) {
        List<MessageInfo> list = messageInfoDao.findListByMessageId(messageId);

        for (MessageInfo messageInfo : list) {
            deleteById(messageInfo.getId());
        }
    }

    @Override
    @Transactional
    public void sendMessageOnTime(Date sendTime, List<MessageInfo> messageInfoList, Boolean flag) {
        for (MessageInfo messageInfo : messageInfoList) {
            messageInfoDao.save(messageInfo);
            if (flag) {
                new MessageTimerWork(sendTime, messageInfo, null, 1);
            }
        }
    }
}